<template>
  <div style="height:100%;width:100%;position:relative;">
      <div class="pagetop">
          <div class="search-title">快速查询</div>
          <el-input v-model="txtsearch" placeholder="菌属名称|代码" style="width:200px"></el-input>
          <!-- <div class="search-title" style="color:blue">提示:选择上级类别下级所有细菌全部默认遵守此规则。</div> -->
          <div class="top-deal">
              <el-button @click="btnQuery" icon="el-icon-search" type="primary" v-has="'PINQUERY'" :disabled="bChangeFlag">查询</el-button>
              <el-button @click="btnAdd" icon="el-icon-plus" v-has="'PADD'" :disabled="bChangeFlag">新增</el-button>
              <el-button @click="btnDel" icon="el-icon-delete" v-has="'PDELETE'" :disabled="bChangeFlag">删除</el-button>
              <el-button @click="btnSave" icon="el-icon-document" v-has="'PMODIFY'" :disabled="!bChangeFlag">保存</el-button>
              <el-button @click="btnClear" icon="el-icon-close" :disabled="!bChangeFlag">取消</el-button>
              <!-- <el-button @click="btnExport" icon="el-icon-upload2">导出</el-button> -->
              <!-- <el-button @click="btnImport" icon="el-icon-download">导入</el-button> -->
          </div>
      </div>
      <div class="pagecenter">
          <div class="middle-center">
              <vxe-table :data.sync="list" :loading="bLoading" :row-class-name="LRowClassName" :cell-class-name="lCellClassName" :select-config="selectConfig" :sort-config="{trigger: 'cell'}" :edit-config="{trigger: 'click', mode: 'cell',showStatus: true,showIcon:false}" @current-change="CurrentChangeEvent" fit height="auto" header-align="center" highlight-current-row highlight-hover-row highlight-hover-column border ref="lXTable" resizable show-header-overflow="tooltip" show-overflow="tooltip" size="mini" stripe class="detailxTable" @edit-disabled="editDisabledEvent"> 
                  <vxe-table-column type="index" title="NO." align="center" width="7%"></vxe-table-column>
                  <vxe-table-column field="germgroupna" title="菌属" width="31%" sortable :disabled="true" :edit-render="{name: 'input',autoselect: true}">
                      <template v-slot:edit="{ row,column }">
                          <el-input placeholder="双击开窗" v-model="row.germgroupna" style="width:100%; color:blue" @keyup.space.native="OpenGermDlg(row,2)" @dblclick.native="OpenGermDlg(row,2)" readonly>
                          </el-input>
                      </template>
                  </vxe-table-column>  
              </vxe-table>
          </div>
          <div class="middle-right" v-loading="bPageInitLoading" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)">
              <div style="height:100%;width:100%;background-color:#ddccbb;" class="detailxTable">
                  <vxe-table :data="rXTableData" :loading="bLoading" :select-config="selectConfig" :sort-config="{trigger: 'cell'}" :edit-config="{trigger: 'click', mode: 'cell',showStatus: true,activeMethod:activeMethod,showIcon:false}" fit border height="auto" header-align="center" highlight-current-row highlight-hover-row highlight-hover-column ref="rXTable" resizable show-header-overflow="tooltip" show-overflow="tooltip" size="mini" stripe :row-class-name="RRowClassName">
                      <!-- <vxe-table-column title="抗生素"> -->
                      <vxe-table-column type="index" title="NO." align="center" width="6%"></vxe-table-column>
                      <vxe-table-column field="germna" title="细菌" width="31%" sortable :disabled="true" :edit-render="{name: 'input',autoselect: true}">
                          <template v-slot:edit="{ row,column }">
                              <el-input placeholder="双击开窗" v-model="row.germna" style="width:100%" @keyup.space.native="OpenGermDlg(row,3)" @dblclick.native="OpenGermDlg(row,3)" readonly>
                              </el-input>
                          </template>
                      </vxe-table-column>
                      <template v-slot:fix>
                          <div style="font-size:12px;padding-top:3px;background-color:#fff;text-align:center">
                              <table style="border-spacing:10px;width:100%">
                                  <tr>
                                      <td>
                                          <el-button @click="$refs.rXTable.insertAt({germgroup:''},-1) .then(({ row }) => {
                      $nextTick(() => {
                          bChangeFlag=true
                          $refs.rXTable.setCurrentRow(row)
                          $refs.rXTable.setActiveCell(
                              row,
                              'germna'
                          )
                          $refs.rXTable.scrollToRow(row)
                      })
                  })">新增明细</el-button>
                                      </td>
                                      <td>
                                          <el-button @click="$refs.rXTable.remove($refs.rXTable.getCurrentRow()),bChangeFlag = true">删除明细</el-button>
                                      </td>
                                  </tr>
                              </table>
                          </div>
                      </template>
                  </vxe-table>
              </div>
          </div>
          <!--菌科弹窗-->
           
          <!--菌属弹窗-->
          <el-dialog v-el-drag-dialog :append-to-body="true" :close-on-click-modal="false" title="请选择菌属" :visible.sync="bDlgGermgroup" :show-close="true" :destroy-on-close="true" v-if="diagx">
              <rm-pop-common ref="refGermgroup" @change="GermGroupChange" @cancel="bDlgGermgroup=false;diagx=false;" datatype="germgroup"></rm-pop-common>
          </el-dialog>
          <!--细菌弹窗-->
          <el-dialog v-el-drag-dialog :append-to-body="true" :close-on-click-modal="false" title="请选择细菌" :visible.sync="bDlgGerm" :show-close="true" :destroy-on-close="true" v-if="diagx">
              <rm-pop-common ref="refGerm" @change="GermChange" @cancel="bDlgGerm=false;diagx=false;" datatype="germ"></rm-pop-common>
          </el-dialog>
      </div>

  </div>
</template>

<script type="text/javascript">
import XEUtils from "xe-utils";
export default {
  name: "LIS814",
  data() {
      return {
          txtsearch: "",
          actionindex: "M",
          param1: "", //pop组件用
          kindno: "", //pop组件用
          oldRowId: "",
          newRowId: "",
          diagx: false, //销毁弹窗数据
          bLoading: false,
          bPageInitLoading: false,
          bChangeFlag: false,
          //弹窗组件-细菌
          bDlgGermkind: false,
          bDlgGermgroup: false,
          bDlgGerm: false,
          //弹窗组件-抗生素
          bDlgMed: false,
          ntempRow: {},
          tempRow: {},
          germRow: {},
          medRow: {},
          selectConfig: { tigger: "row" },
          selrow: [],
          AddData: [],
          ModData: [],
          lXTableData: [],
          rXTableData: [],
          TplXTableData: [],
          ogroupitemcode:"",
      };
  },
  created() {
      this.btnQuery();
  },
  watch: {
      txtsearch(val) {
          let row = this.list[0];
          if (row) {
              this.HightLightRow(row);
          } else {
              this.HightLightRow(false);
          }
      },
  },
  computed: {
      //模糊查询  名称|代码|级别:菌科1菌属2细菌3
      list() {
          let filterName = this.txtsearch.trim();
          if (filterName) {
              let rest = this.lXTableData.filter((item) => {
                  return item.germgroup.toUpperCase().indexOf(filterName.toUpperCase()) > -1 || (item.germgroupna ? item.germgroupna.toUpperCase().indexOf(filterName.toUpperCase()) > -1 : false);
              });
              return rest;
          } else {
              return this.lXTableData;
          }
      },
  },
  mounted() {},
  updated() {},
  methods: {
      //------------------编辑类 ------------------//
      activeCellMethod({ column, columnIndex }) {
          return columnIndex !== 1;
      },
      activeRowMethod({ row, rowIndex }) {
          return rowIndex !== 1;
      },
      editDisabledEvent({ row, column }) {
          this.$XMsg.alert("禁止编辑");
      },
      //----------------- 查询类 ----------------- //
      //主表查询
      btnQuery() {
          this.AddData = [];
          this.ModData = [];
          this.bLoading = true;
          this.$tool
              .request({
                  url: "LIS/LIS8/LIS814",
                  method: "post",
                  data: {
                      action: "btn_query_group",
                  },
              })
              .then((res) => {
                  this.lXTableData = res.RData.Data;
                  this.TplXTableData = XEUtils.clone(res.RData.Data, true);
                  if (this.lXTableData.length == 0) this.actionindex = "A";
                  if (this.actionindex == "C") {
                      // this.HightLightRow(this.tempRow)
                      this.actionindex = "M";
                  } else {
                      this.HightLightRow(res.RData.Data[0]);
                      // this.germcodeno = res.RData.Data[0].germcodeno
                  }

                  this.bLoading = false;
              })
              .catch((err) => {
                  this.bLoading = false;
              });
      },
      //明细查询 -- 主表，子表
      async detailQuery(row) {
          try {
              this.selrow = row;
              setTimeout(() => {
                  this.tempRow = XEUtils.clone(row, true);
                  if (row._XID != null) {
                      this.oldRowId = XEUtils.clone(row._XID, true);
                  } else this.oldRowId = [];
              }, 10);
              this.actionindex = "M";
              this.bPageInitLoading = true;
              const res = await this.$tool.request({
                  url: "LIS/LIS8/LIS814",
                  method: "post",
                  data: {
                      action: "btn_query_germ",
                      germcodeno: row.germgroup,
                  },
              });
              console.log("res", res);
              if (res.data.length > 0) {
                  this.rXTableData = res.data;
                  this.$refs.rXTable.setCurrentRow(this.rXTableData[0]);
              } else {
                  this.rXTableData = [];
              }
              this.bPageInitLoading = false;
          } catch (e) {
              this.bPageInitLoading = false;
              this.$message.error(e);
          }
      },
      GKind(germ, germgroup) {
          this.$tool
              .request({
                  url: "LIS/LIS8/LIS827",
                  method: "post",
                  data: {
                      action: "ddl_germkind",
                      germ: germ,
                      germgroup: germgroup,
                  },
              })
              .then((res) => {
                  if (res.data.length > 0) {
                      this.germRow.germkind = res.data[0].germkindcode;
                      this.germRow.germkindna = res.data[0].germkindname;
                  } else {
                      this.germRow.germkind = "";
                      this.germRow.germkindna = "";
                  }
              });
      },
      GGroup(germ) {
          this.$tool
              .request({
                  url: "LIS/LIS8/LIS827",
                  method: "post",
                  data: {
                      action: "ddl_germgroup",
                      germ: germ,
                  },
              })
              .then((res) => {
                  if (res.data.length > 0) {
                      this.germRow.germgroup = res.data[0].rpt_itemcode;
                      this.germRow.germgroupna = res.data[0].rpt_itemname;
                  } else {
                      this.germRow.germgroup = "";
                      this.germRow.germgroupna = "";
                  }
              });
      },
      //----------------- 按钮类 -----------------//
      //新增
      btnAdd() {
          // this.bChangeFlag = true
          this.actionindex = "A";
          this.$refs.lXTable.insertAt({}, -1);
          this.FunscrollY();
          this.rXTableData = [];
          // this.$nextTick(() => {
          //     this.$refs.rXTable.insertAt({ germgroup: "" }, -1);
          //     this.$refs.rXTable.updateListenter();
          // });

          this.bChangeFlag = true;
      },
      //删除 -- 弹窗提示
      btnDel() {
          var name =this.tempRow.germgroupna;
          this.$confirm("您确定要删除<span style='color:red;font-weight: 700'>" + name + "</span>的所有的细菌吗？", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              dangerouslyUseHTMLString: true,
              type: "warning",
          })
              .then(() => {
                  this.actionindex = "D";
                  this.confirmDel();
              })
              .catch(() => {});
      },
      //删除 -- 确认删除
      async confirmDel() {
          try {
              var delrow = this.$refs.lXTable.getCurrentRow();
              if (delrow) {
                  var alld = this.$refs.lXTable.tableData;
                  var rowindex = alld.indexOf(delrow);
                  this.$refs.lXTable.remove(delrow);
                  await this.btnSave().then(() => {
                      this.lXTableData.splice(rowindex, 1)
                      let havedata = this.$refs.lXTable.tableData;
                      if (havedata.length > 0) {
                          if (rowindex >= havedata.length) rowindex = havedata.length - 1;
                          let selectrow = havedata[rowindex];
                          this.HightLightRow(selectrow);
                      } else {
                          this.HightLightRow(false);
                      }
                  });
              }
          } catch (e) {
              this.$message.error(e);
          }
      },
      //取消 -- 取消操作，数据还原
      btnClear() {
          this.$confirm("您确定要取消这次改动吗？", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
          })
              .then(() => {
                  this.bChangeFlag = false;
                  this.lXTableData = XEUtils.clone(this.TplXTableData, true);
                  if (this.actionindex == "A") {
                      setTimeout(() => {
                          let last = this.$refs.lXTable.tableData[this.$refs.lXTable.tableData.length - 1];
                          this.$refs.lXTable.setCurrentRow(last);
                          this.detailQuery(last);
                      }, 30);
                  } else {
                      let a = this.lXTableData.filter((item) => item.germgroup == this.tempRow.germgroup);
                      setTimeout(() => {
                          this.tempRow._XID = a[0]._XID;
                          this.$refs.lXTable.setCurrentRow(this.tempRow);
                          this.detailQuery(this.tempRow);
                      }, 30);
                  }
                  this.actionindex = "C";
              })
              .catch(() => {});
      },
      //保存 -- 保存新增，修改，删除 
      async btnSave() {
          console.log("this.tempRow",this.tempRow);
          console.log("this.selrow",this.selrow);
          let ogermgroup = this.tempRow.germgroup;
          let ngermgroup = "";
          //通过_XID获取修改后的代码
          this.$refs.lXTable.getRowById(this.oldRowId);
          if (this.$refs.lXTable.getRowById(this.oldRowId) != null) {
              ngermgroup = this.$refs.lXTable.getRowById(this.oldRowId).germgroup;
              //nLevelno = this.$refs.lXTable.getRowById(this.oldRowId).levelno;
          } else {
              //获取新增菌属代码
              ngermgroup = this.ntempRow.germgroup;
              //nLevelno = this.ntempRow.levelno;
          }
          // }
          let medArr = this.$refs.rXTable.getTableData().fullData;
          let insrtArr = [];
          if (this.actionindex != "D") {
              medArr.forEach((element) => {
                  let groupitemcode = ngermgroup;
                  let itemcode = element.germno;
                  let levelno = 3;
                  let s = {
                      groupitemcode: groupitemcode,
                      itemcode: itemcode,
                      levelno: levelno,
                  };
                  insrtArr.push(s);
              });
          }
          try {
              const res = await this.$tool.request({
                  url: "LIS/LIS8/LIS814",
                  method: "post",
                  data: {
                      action: "btn_save",
                      ogermgroup:ogermgroup,
                      ngermgroup:ngermgroup,
                      insrtarr: insrtArr,
                      act: this.actionindex,
                  },
              });
              if (res.errcode == "1") {
                  this.$message.success("保存成功！");
                  this.$refs.lXTable.updateListenter();
                  this.bChangeFlag = false;
                  if (this.actionindex == "A") {
                      if (this.AddData.indexOf(nGermcodeno) == -1) {
                          this.AddData.push(this.tempRow);
                      }
                      let tabledata = this.$refs.lXTable.updateData();
                      console.log("tabledata", tabledata);
                      this.tempRow = this.$refs.lXTable.getCurrentRow();
                  } else if (this.actionindex == "M") {
                      //if (this.ModData.indexOf(oGermcodeno) == -1) this.ModData.push(this.$refs.lXTable.getRowById(this.oldRowId));
                      this.detailQuery(this.$refs.lXTable.getCurrentRow());
                  } else {
                      this.actionindex = "M";
                  }
                  // if (this.$refs.rXTable.tableData.length == 0 || this.$refs.rXTable.tableData == null) {
                  //     var alld = this.$refs.lXTable.tableData;
                  //     var rowindex = alld.indexOf(this.selrow);
                  //     this.lXTableData.splice(rowindex, 1);
                  // }
                  this.TplXTableData = XEUtils.clone(this.$refs.lXTable.getTableData().fullData);
                  this.actionindex = "M";
              } else {
                  this.$message.error("保存失败！" + res.errmsg);
              }
          } catch (e) {
              this.$message.error(e);
          }
      },
      //导出
      btnExport() {
          let p = { prgno: "LIS814" };
          this.$pub.commexport(this, p, `血培养污染菌.dat`);
      },
      //导入 -- 暂无
      btnImport() {},
      //--------------- 数据改变及其他功能 ---------------//
      //行改变事件
      async CurrentChangeEvent({ row }) {
          if (this.bChangeFlag) {
              this.$refs.lXTable.setCurrentRow(this.selrow);
              return false;
          } else {
              await this.detailQuery(row);
          }
      },
      //保存后不刷新左侧主表,前台赋值。
      SetToTable(obj) {
          return new Promise((s, f) => {
              s(this.selrow);
              return;
          });
      },
      // 回车换行
      NextFocus(index) {
          if (index > 4) return false;
          var that = this;
          var focusIndex = index + 1;
          setTimeout(function () {
              that.$refs["input" + focusIndex].focus();
          }, 1);
      },
      activeMethod({ row }) {
          return true;
      }, 
      //数据发生改变 -- 按钮禁用/可用切换
      HasChange(e) {
          console.log(e);
          this.bChangeFlag = true;
      }, 
      //设置高亮选中行
      async HightLightRow(row) {
          if (!!row) {
              this.$refs.lXTable.setCurrentRow(row);
              await this.detailQuery(row);
          } else {
              this.$refs.lXTable.setCurrentRow(null);
              this.tempRow = {};
              this.detailData = {};
              this.tmpdetailData = {};
              this.rXTableData = [];
          }
      },
      //细菌类弹窗
      OpenGermDlg(row, flag) {
          if (!this.bChangeFlag) {
              this.newRowId = row._XID;
          } else {
              this.newRowId = row._XID;
          }
          
          this.germRow = row;
          if (flag == 1) {
              // this.diagx = true;
              // this.bDlgGermkind = true;
              // this.$nextTick(() => {
              //     this.$refs.refGermkind.loadAllData();
              // });
          } else if (flag == 2) {
              if (this.bChangeFlag) {
              //编辑状态
                  if (this.oldRowId != this.newRowId) return false; //rowId不相等 禁止编辑
              }
              //this.kindno = row.germkind;
              this.diagx = true;
              this.bDlgGermgroup = true;
              this.$nextTick(() => {
                  this.$refs.refGermgroup.loadAllData();
              });
          } else if (flag == 3) {
              this.diagx = true;
              this.bDlgGerm = true;
              this.$nextTick(() => {
                  this.$refs.refGerm.loadAllData();
              });
          }
      }, 
      //菌属改变
      GermGroupChange(c, v) {

          var data=this.$refs.lXTable.tableData;
          if(data.filter((item) => c == item.germgroup && item._XID !=this.selrow._XID).length>0){
              this.$alert("所选菌属已存在，请重新选择");
              return false;
          }else{
              this.HasChange();
              //this.GKind("", c);
              //值
              //this.tempRow.germgroup = c;
              //this.tempRow.germgroupna = v;
              this.germRow.germgroup = c;
              this.germRow.germgroupna = v;
              setTimeout(() => {
                  this.$refs.lXTable.setCurrentRow(this.selrow);
              }, 30);
              this.AddLastFocus();
              this.bDlgGermgroup = false;
          }

      },
      //细菌改变
      GermChange(c, v) {
          this.HasChange();
          //this.GKind(c, "");
          //this.GGroup(c);
          this.$nextTick(() => {
              this.germRow.levelno = 3;
              this.germRow.germno = c;
              this.germRow.germna = v;
              setTimeout(() => {
                  this.$refs.lXTable.setCurrentRow(this.selrow);
              }, 30);
              this.AddLastFocus();
              this.bDlgGerm = false;
          });
      },
     
      FunscrollY() {
          this.$nextTick(() => {
              var alldataLen = this.$refs.lXTable.tableData.length;
              let L = this.$refs.lXTable.tableData[alldataLen - 1];
              this.selrow = L;
              this.$refs.lXTable.setCurrentRow(L);
              // this.$refs.lXTable.setActiveCell(L, 'germkindna')
              this.$refs.lXTable.scrollToRow(L);
              this.oldRowId = XEUtils.clone(L._XID, true);
              this.tempRow = XEUtils.clone(L, true);
              this.ntempRow = L;
              //if (this.AddData.indexOf(L.medcode) == -1) this.AddData.push(L);
          });
      }, 
      AddLastFocus() {
          console.log("1");
          if (this.actionindex == "A") {
              console.log("a");
              this.$refs.rXTable.setActiveCell(this.$refs.rXTable.getTableData().fullData[this.$refs.rXTable.getTableData().fullData.length - 1], "germna");
          }
      }, 
      //----------------- class -----------------//
      //左侧主表 row class
      LRowClassName({ row, rowIndex }) {
          let isDirty = this.$refs.lXTable.hasRowChange(row);
          if (isDirty) {
              return "row-modify";
          }
          if (this.$refs.lXTable.hasRowInsert(row)) {
              return "row-new";
          }
      },
      //右侧子表 row class
      RRowClassName({ row, rowIndex }) {
          let isDirty = this.$refs.rXTable.hasRowChange(row);
          if (isDirty) {
              return "row-modify";
          }
          if (this.$refs.rXTable.hasRowInsert(row)) {
              return "row-new";
          }
      },
      lCellClassName({ row, rowIndex, $rowIndex, column }) {
          if (column.property == "germkind") {
              if (row.levelno == 1) {
                  return "isGermcodeno";
              }
          } else if (column.property == "germgroup") {
              if (row.levelno == 2) return "isGermcodeno";
          } else if (column.property == "germ") {
              if (row.levelno == 3) return "isGermcodeno";
          }
      },
      
  },
};
</script>

<style scoped>
.pagetop {
  width: 100%;
  height: 35px;
  display: -webkit-box;
  -webkit-box-pack: left;
  -webkit-box-align: center;
  border: 1px solid #ccc;
  position: absolute;
  z-index: 99;
}

.pagecenter {
  position: absolute;
  top: 40px;
  width: 100%;
  left: 0;
  bottom: 0px;
  overflow: auto;
}

.middle-center {
  position: absolute;
  height: 100%;
  left: 0px;
  right: 49%;
  overflow: auto;
  border: 1px solid #ccc;
}

.middle-right {
  position: absolute;
  height: 100%;
  /* width: 50%; */
  left: 51%;
  padding-left: 3px;
  right: 0px;
  border: 1px solid #ccc;
}

.search-title {
  margin: 0 5px 0 20px;
  font-size: 12px;
}
.top-deal {
  right: 5px;
  position: absolute;
  top: 5px;
  display: flex;
  align-items: center;
}
.detailxTable {
}
/deep/.el-textarea__inner {
  display: block;
  resize: vertical;
  padding: 2px 4px;
}
/deep/ .el-button.is-disabled {
  border: 0px;
  color: grey;
  background-color: #e6e6e6;
  font-weight: normal;
}
/deep/ tr.vxe-body--row.row-modify {
  color: blue;
}
/deep/ tr.vxe-body--row.row-new {
  color: #cc6600;
}
/deep/.vxe-cell.isGermcodeno {
  background-color: #cc6600;
  color: blue;
  font-weight: bold;
}
.table1style tr td {
  padding: 0px 2px 0px 2px;
}
</style>